#!/bin/bash

set -euo pipefail

SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
source ${SCRIPT_DIR}/common

# Expect base collection path as an argument
BASE_COLLECTION_PATH=$1

# Use PWD as base path if no argument is passed
if [ "${BASE_COLLECTION_PATH}" = "" ]; then
    BASE_COLLECTION_PATH=$(pwd)
fi

NAMESPACE=${2:-openshift-logging}

CLO_COLLECTION_PATH="$BASE_COLLECTION_PATH/cluster-logging"
# Adding namespace folders to allow for multi-logging
collector_folder="$CLO_COLLECTION_PATH/namespaces/$NAMESPACE"

log "- BEGIN <gather_collection_resources> for namespace: $NAMESPACE ..."

log "-- Exporting ClusterLogForwarder.observability.openshift.io resources"
crs="$(oc get clusterLogForwarder.observability.openshift.io -n $NAMESPACE -o custom-columns=:.metadata.name)"

# get name of collector from CR name
for collector in ${crs}; do
  log "-- Gathering data for ClusterLogForwarder: $collector"
  mkdir -p $collector_folder
  oc -n $NAMESPACE get clusterLogForwarder.observability.openshift.io/$collector -o yaml > $collector_folder/$collector.yaml --cache-dir=${KUBECACHEDIR} 2>&1

  # find daemonset
  log "--- Describe Daemonset ds/$collector"
  ds_describe=$(oc -n $NAMESPACE describe ds/$collector --cache-dir=${KUBECACHEDIR} 2>&1)||
  if [ "$?" == "0" ]; then
    echo "$ds_describe" > $collector_folder/$collector.describe
  fi

  # gathering collector pods
  pods="$(oc -n $NAMESPACE get pods -lapp.kubernetes.io/instance=$collector -lapp.kubernetes.io/component=collector -o custom-columns=:.metadata.name)"
  for pod in $pods
  do
      log "--- Describe collector pod: $pod"
      oc -n $NAMESPACE describe pod/$pod > $collector_folder/$pod.describe --cache-dir=${KUBECACHEDIR} 2>&1
  done

  config_name="$collector-config"
  log "-- Gathering $config_name#vector.toml from namespace: $NAMESPACE"
  data=$(oc -n $NAMESPACE get "configmap/$config_name" -o jsonpath='{.data.vector\.toml}' --ignore-not-found)
  if [ "$data" != "" ] ; then
    echo "$data"  > $collector_folder/configmap_${config_name}_vector.toml 2>&1
  fi
done
log "- END <gather_collection_resources> for namespace: $NAMESPACE ..."
